from django import forms
from web import models
from web.forms.bootstrapbase import BootStrapForm
from django.core.exceptions import ValidationError
from web.forms.widgets.colorselect import colorRadioSelect


class addProjectForm(BootStrapForm, forms.ModelForm):

    bootstrap_class_exclude = ['color']

    class Meta:
        model = models.Project
        fields = ['name', 'color', 'desc']
        widgets = {
            'color': colorRadioSelect,
            'desc': forms.Textarea,
        }

    def __init__(self, request, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.request = request

    def clean_name(self):
        name = self.cleaned_data.get('name')
        # 一个人不允许创建两个相同名字的项目
        # 获取用户信息需要引入request对象
        exists = models.Project.objects.filter(creator=self.request.login_user.user, name=name).first()
        if exists:
            raise ValidationError('项目已存在')
        # self.request.login_user.user
        # 额度是否够用，如果额度满了不能继续创建
        used = models.Project.objects.filter(creator=self.request.login_user.user).count()
        haved = self.request.login_user.price_policy.project_num
        if int(used) >= int(haved):
            raise ValidationError('额度已用尽， 请升级超级会员')
        return name
